package com.wizz.trade.common;

import com.wizz.trade.common.constant.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author fyftless
 * 全局异常管理器
 */

@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResponseResult<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2];
            return new ResponseResult<>(StatusCode.ERROR, msg+"已存在");
        }
        return new ResponseResult<>(StatusCode.ERROR, "未知错误");
    }

    @ExceptionHandler(ServiceException.class)
    public ResponseResult<String> exceptionHandler(ServiceException ex){
        log.error("业务逻辑异常 ==> " + ex.getMessage());
        return new ResponseResult<>(StatusCode.ERROR, ex.getMessage());
    }
}